<template>
  <div class="flex">
    <el-card class="w-1/5 tpl" :gutter="12" shadow="always">
      <template #header>
        <div class="card-header">
          <span>资源列表</span>
        </div>
      </template>
      <el-input v-model="filterText" placeholder="搜索文件夹" />
      <el-scrollbar height="650">
        <el-tree
          ref="treeRef"
          node-key="id"
          default-expand-all:false
          :data="folderOptions"
          :props="treeProps"
          :highlight-current="true"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-click="handleFolderClick"
        />
      </el-scrollbar>
    </el-card>
    <el-card class="w-4/5 tpl" style="margin-left: 10px" :gutter="12" shadow="hover">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="名称" prop="filename">
            <el-input
              v-model="queryParams.filename"
              placeholder="请输入名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <!-- 操作：新增 -->
            <XButton
              type="primary"
              preIcon="ep:zoom-in"
              :title="t('action.add')"
              v-hasPermi="['cms:res:create']"
              @click="openForm('create', queryParams.root)"
            />
            <XButton
              type="primary"
              preIcon="ep:zoom-in"
              :title="t('cms.createDir')"
              v-hasPermi="['cms:res:create']"
              @click="handleCreateDir()"
            />
            <XButton
              type="primary"
              preIcon="ep:upload"
              :title="t('cms.upload')"
              v-hasPermi="['cms:res:create']"
              @click="uploadDialogVisible = true"
            />
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :max-height="tableHeight">
          <el-table-column label="名称" key="filename">
            <template #default="{ row }">
              <el-tag v-if="row.directory" @click="handleFolderClick(row)">{{
                row.filename
              }}</el-tag>
              <el-tag v-if="!row.directory&&row.editable" @click="openForm('update', queryParams.root, row.name)">
                {{ row.filename }}</el-tag
              >
              <el-tag  v-if="!row.directory&&!row.editable" >
                {{ row.filename }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="大小" align="center" prop="size" />
          <el-table-column
            label="最后修改时间"
            align="center"
            prop="lastModifiedDate"
            :formatter="dateFormatter"
            width="180"
          />
          <el-table-column label="操作" align="center" width="160">
            <template #default="{ row }">
              <div class="flex justify-center items-center">
                <!-- 操作：编辑 -->
                <XTextButton
                  preIcon="ep:edit"
                  :title="t('action.edit')"
                  v-hasPermi="['cms:tpl:update']"
                  v-if="row.editable"
                  @click="openForm('update', queryParams.root, row.name)"
                />
                <!-- 操作：删除 -->
                <XTextButton
                  preIcon="ep:delete"
                  :title="t('action.del')"
                  v-hasPermi="['cms:tpl:delete']"
                  @click="handleDelete(row.name)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </el-card>
  </div>
  <ResForm ref="formRef" @success="getList" />

  <!--创建文件夹--->
  <Dialog v-model="createDirDialogVisible" :title="createDirDialogTitle" width="500px">
    <el-form class="drawer-multiColumn-form" label-width="150px">
      <el-form-item label="模板文件夹:">
        <el-input v-model="dirName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <XButton
        type="warning"
        preIcon="ep:upload-filled"
        :title="t('action.save')"
        @click="handleSaveDir()"
      />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="createDirDialogVisible = false" />
    </template>
  </Dialog>
  <!---上传文件-->
  <Dialog v-model="uploadDialogVisible" :title="uploadDialogTitle">
    <el-upload
      ref="uploadRef"
      :action="uploadResUrl"
      :headers="uploadHeaders"
      :data="uploadData"
      :drag="true"
      :multiple="true"
      :show-file-list="true"
      :disabled="uploadDisabled"
      :before-upload="beforeUpload"
      :on-success="handleFileSuccess"
      :on-error="excelUploadError"
      :auto-upload="false"
    >
      <Icon icon="ep:upload-filled" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip"
          >请上传 woff2, eot, woff, ttf, svg, jpg, jpeg, png, gif, css, js, bmp, ico, map,mp4, m4v,
          mov, qt, avi, flv, wmv, asf, mpeg, mpg, vob, rmvb, rm, ts, 3gp, asf, wmv, mkv, dat, mp3,
          wav, aif, au, ram, wma, mmf, amr, flac, aac, cur, htc, swf 文件</div
        >
      </template>
    </el-upload>
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton
        type="primary"
        preIcon="ep:upload-filled"
        :title="t('action.save')"
        @click="submitFileForm()"
      />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="uploadDialogVisible = false" />
    </template>
  </Dialog>
</template>
<script setup lang="ts" name="TPL">
import ResForm from './ResForm.vue'
import type { ElTree, UploadInstance, UploadRawFile } from 'element-plus'
import { handleTree } from '@/utils/tree'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { treeProps } from './res.data'
import * as ResApi from '@/api/cms/res'
import { getSiteHeader } from '@/utils/cmscommon'
import { dateFormatter } from '@/utils/formatTime'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数
const tableHeight = ref(800)
const queryParams = reactive({
  root: '',
  filename: null
})

const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ResApi.getResListApi(queryParams)
    list.value = data
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, root: string, name?: string) => {
  formRef.value.open(type, root, name)
}

// ========== 创建左侧树结构 ==========
const filterText = ref('')
const folderOptions = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const getTree = async () => {
  const res = await ResApi.getResTreeApi()
  folderOptions.value.push(...handleTree(res))
}

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
const handleFolderClick = async (row: { [key: string]: any }) => {
  queryParams.root = row.name
  await getList()
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
// ========== CRUD 相关 ==========

const handleCreateDir = async () => {
  createDirDialogVisible.value = true
}

/** 删除按钮操作 */
const handleDelete = async (name: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ResApi.deleteResApi(name)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
// 文件上传
const uploadDialogVisible = ref(false)
const uploadDialogTitle = ref('上传')
const uploadDisabled = ref(false)
const uploadImportDisabled = ref(false)
const uploadRef = ref<UploadInstance>()
const uploadImportRef = ref<UploadInstance>()
const uploadHeaders = ref()
const uploadData = ref()
let uploadResUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/cms/siteres/upload'
// 文件上传之前判断
const beforeUpload = (file: UploadRawFile) => {
  console.log(file.type)
  const isHtml = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
  if (!isHtml) message.error('上传文件只能是 html 格式!')
  return isHtml
}
// 文件上传
const submitFileForm = () => {
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId(),
    'jprocms-site-id': getSiteHeader()
  }
  //上传目标文件夹
  uploadData.value = {
    root: queryParams.root || ''
  }
  uploadDisabled.value = true
  uploadRef.value!.submit()
}

// 文件上传成功
const handleFileSuccess = async (response: any): Promise<void> => {
  if (response.code !== 0) {
    uploadDisabled.value = false
    message.error(response.msg)
    return
  }
  message.success('上传成功')
  uploadDialogVisible.value = false
  uploadDisabled.value = false

  uploadImportDisabled.value = false
  await getList()
}
// 上传错误提示
const excelUploadError = (): void => {
  message.error('导入数据失败，请您重新上传！')
  uploadDisabled.value = false
  uploadImportDisabled.value = false
  uploadImportRef.value?.clearFiles
  uploadRef.value?.clearFiles
}
//创建文件夹
const createDirDialogVisible = ref(false)
const createDirDialogTitle = ref('创建文件夹')
const dirName = ref('')
const handleSaveDir = async () => {
  const data = {
    dirName: dirName.value,
    root: queryParams.root
  }
  console.log('queryParams->', queryParams)
  console.log('data->', data)
  try {
    await ResApi.createDirApi(data)
  } finally {
    // 刷新列表
    await getList()
    loading.value = false
  }
  message.success(t('common.createSuccess'))
  dirName.value = ''
  createDirDialogVisible.value = false
}

// ========== 初始化 ==========
onMounted(async () => {
  await getTree()
  await getList()
})
</script>

<style scoped>
.tpl {
  height: 780px;
  max-height: 800px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-link {
  margin-right: 8px;
}

.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
</style>
